<?php

namespace app\common\controller;

use app\common\utils\ApiReturn;
use app\common\utils\Init;
use app\common\utils\MyLog;
use think\App;
use think\exception\ValidateException;
use think\Validate;

/**
 * controller公共基础类
 */
class CommonBaseController
{
    /**
     * 应用实例
     * @var App
     */
    protected $app;

    /**
     * 请求参数
     */
    protected $params;

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        try{
            //初始化设置
            $this->initSet();
            $this->app = $app;

            //获取请求参数, 并记录到log
            $params = $app->request->post();
            MyLog::record()->info($params, 'request');
            $this->params = $params; //设置controller层可以快速访问
            Init::$post_data = $params; //设置全局可以访问
        }catch (\Exception | \Error $e){
            ApiReturn::retError($e);
        }
    }

    public function initSet()
    {
        Init::setRequestId();
        Init::setRequestStartTime();
        Init::setLogSuffix('api');
    }

    /**
     * 验证数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @return array|string|true
     * @throws ValidateException
     */
    protected function checkParams($validate = [])
    {
        $data = $this->params;
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                list($validate, $scene) = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }
        return $v->failException(true)->check($data);
    }

}